#include "../../inc/my_sqlite3.h"

int register_new_user(sqlite3*pdb,char*username,char*password)
{
    int ret = 0;
    char sql[128]= ""; 
    int rows = 0 ;
    int cols = 0;
    char **presult ;
    sprintf(sql,"SELECT * FROM user WHERE name ='%s'",username);
    char * perrmsg = NULL;
    ret = my_sqlite3_get_table(pdb,sql,&presult,&rows,&cols,&perrmsg);
    if(ret != SQLITE_OK)
    {
	sqlite3_free(perrmsg);
	perrmsg = NULL;
	pdb = NULL;
	return -1;
    }
    if(rows!= 0)
    {
	printf("用户%s已存在,无法注册\n",username);
	
	return 1;
    }
    if(rows ==0 )
    {
	sprintf(sql,"insert into user values('%s','%s',0)", username,password);
	ret = my_sqlite3_exec(pdb,sql,NULL,NULL,&perrmsg);
	if(ret != SQLITE_OK)
 	{
 	    printf("注册失败\n");
	    sqlite3_free(perrmsg);
	    perrmsg = NULL;
	    sqlite3_close(pdb);
	    pdb = NULL;
	    return -2;
	}
	printf("注册了一个新用户\n");
    }
    return 0;
}

int update_login_flag(sqlite3*pDB,char*username,int flag)
{
    int ret = 0;
    char sql[128]= "";
    sprintf(sql,"UPDATE user SET flag = %d WHERE name = '%s'",flag,username);
    char * perrmsg = NULL;
    ret = my_sqlite3_exec(pDB,sql,NULL,NULL,&perrmsg);
    if(ret != SQLITE_OK)
    {
	sqlite3_free(perrmsg);
	perrmsg = NULL;
	sqlite3_close(pDB);
	pDB = NULL;
	return 1;
    }
    return 0;
}


int user_login(sqlite3*pdb,char*username,char*password)
{
    int ret = 0;
    char sql[128]= "";
    char **presult;
    int rows = 0;
    int cols = 0;
    sprintf(sql,"SELECT name,password,flag from user where name = '%s'", username);
    char * perrmsg = NULL;
    ret = my_sqlite3_get_table(pdb,sql,&presult,&rows,&cols,&perrmsg);
    if(ret != SQLITE_OK)
    {
	sqlite3_free(perrmsg);
	perrmsg = NULL;
	sqlite3_close(pdb);
	pdb = NULL;
	return -1;
    }
    if(rows == 0 )
    {
	printf("该用户不存在\n");
	sqlite3_free(perrmsg);
	perrmsg = NULL;
	sqlite3_close(pdb);
	pdb = NULL;
	return 1;
    }
    if(rows!=0)
    {
	if(strcmp(password,*(presult+rows+cols)))
	{
	    printf("密码错误\n");
	    sqlite3_free_table(presult);
	    presult = NULL;
	    return 3;
    
	}
	if(strcmp(*(presult+rows+cols+1),"1")==0)
	{
	    printf("该用户已登录\n");
	    sqlite3_free(perrmsg);
	    perrmsg = NULL;
	    sqlite3_close(pdb);
	    pdb = NULL;
	    return 2;
	}
	if(strcmp(*(presult+rows+cols+1),"0")== 0 && strcmp(password,*(presult+rows+cols))==0)
	{
	    sqlite3_free_table(presult);
	    presult = NULL;
	    update_login_flag(pdb,username,1);
	    return 0;
	}
    }
    return 0;
}

